import { TypedUseSelectorHook, useDispatch as useReduxDispatch, useSelector as useReduxSelector } from "react-redux";
import { configureStore, combineReducers, Middleware } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import { thunk } from "redux-thunk";
import storage from "redux-persist/lib/storage";
import user from "@/redux/modules/user"
import auth from "@/redux/modules/auth"

const reducer = combineReducers({ user, auth });

// redux persist 持久化配置
const persistConfig = {
  key: "redux-state",
  storage: storage,
  blacklist: ["auth"]
};
const persistReducerConfig = persistReducer(persistConfig, reducer);

// redux middleWares(self configuration) 异步中间件
const middleWares: Middleware[] = [thunk];

// store
export const store = configureStore({
  reducer: persistReducerConfig,
  middleware: getDefaultMiddleware => getDefaultMiddleware({ serializableCheck: false }).concat(middleWares),
  devTools: true
});

// create persist store
export const persistor = persistStore(store);

// redux hooks
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector;
export const useDispatch = () => useReduxDispatch<AppDispatch>();
